<template>
    <!--用户编辑对话框-->
    <el-dialog 
     title="编辑用户"
     v-model="editVisible"
     width="50%"  
     center
     @close="closeedit"
    >
    <el-form
       ref="ruleFormRef"
       :model="edituserForm"
       :rules="rules"
     >
       <el-form-item label="用户名" prop="userName">
         <el-input v-model="edituserForm.userName" />
       </el-form-item>
       <el-form-item label="密码" prop="userPwd">
         <el-input v-model="edituserForm.userPwd" />
       </el-form-item>
       <el-form-item label="邮箱" prop="userMail">
         <el-input v-model="edituserForm.userMail" />
       </el-form-item>
       </el-form>
    <template #footer>
       <span class="dialog-footer">
           <el-button @click="editVisible = false">取消</el-button>
           <el-button type="primary" @click="edituser">确定</el-button>
       </span>
    </template>
    </el-dialog>
       </template>

<script setup>
import { useUsersStore } from "../store/user"
import { storeToRefs } from "pinia"
import { ref, reactive } from "vue"
import axios from "axios";
let store = useUsersStore()
let { editVisible, edituserForm } = storeToRefs(store)

//自定义邮箱规则
var checkEmail = (rule, value, callback) => {
    let reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if (reg.test(value)) {
        return callback()
    } else {
        callback(new Error("请输入合法邮箱"))
    }
}
let rules = reactive({
    userName: [
        { required: true, message: "请填写用户名", trigger: 'blur' },
        { min: 3, max: 10, message: "字符长度在3-10", trigger: 'blur' }
    ],
    userPwd: [
        { required: true, message: "请填写密码", trigger: 'blur' },
        { min: 6, max: 15, message: "字符长度在6-15", trigger: 'blur' }
    ],
    userMail: [
        { required: true, message: '请填写邮箱', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' }
    ]
})
let ruleFormRef = ref()
//关闭对话框
function closeedit() {
    ruleFormRef.value.resetFields()
}
//点击确定，进行编辑
function edituser() {
    ruleFormRef.value.validate((bool) => {
        if (!bool) return
        axios.post("/users/edit", store.edituserForm).then((res) => {
            store.userloadData()
            store.editVisible = false
        })
    })
}
</script>

<style scoped>

</style>